package com.zzy.pool.pool2.mypool;

import java.io.Closeable;
import java.io.IOException;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class Pool<T> implements Closeable {
	public GenericObjectPool<String> innerPool;

	public Pool() {

	}

	public Pool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory<String> factory) {
		initPool(poolConfig, factory);
	}

	public void close() throws IOException {
		innerPool.close();
	}

	public void initPool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory<String> factory) {
		if (this.innerPool != null) {
			System.out.println("innerPool is not null,destroy it..");
			innerPool.close();
		}
		this.innerPool = new GenericObjectPool<String>(factory, poolConfig);
	}

	public String getResource() {
		String str = "";
		try {
			str = this.innerPool.borrowObject();
			System.out.println("get resource success..:" + str);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("get resource error...");
		} finally {
			return str;
		}
	}
	
	
	


	public void returnResourceObject(final String resource) {
		if (resource == null) {
			return;
		}
		innerPool.returnObject(resource);
		System.out.println("return resource success.." + resource);
	}

}